import React, {
  FC,
  CSSProperties,
  Children,
  useContext,
  useEffect,
  useState,
  useCallback,
} from 'react';
import classNames from 'classnames';
import TreeNode from './treeNode';

type treeDataType = {
  title: string | number;
  key: string | number;
  children?: treeDataType[];

  levelPath?: []; // 层级路径
  level?: []; // 层级
};

export interface treeTypeProps {
  className?: string;
  style?: CSSProperties;
  treeData: treeDataType[];
  isExpand?: boolean; // 是否展开
}

const zl = (list: treeDataType[]) => {
  return list;
};

export const tree: FC<treeTypeProps> = props => {
  const [rowList, setRowList] = useState<any>([]);

  // 数据变化重新初始化
  useEffect(() => {
    setRowList(zl(props.treeData) || []); // 应该深拷贝
  }, [props.treeData]);

  // 展开
  const onClickExpand = useCallback(
    (key: number | string) => {
      // debugger;
      const rowListTrans = [...rowList];
      for (let i = 0; i < rowList.length; i += 1) {
        if (rowList[i].key === key) {
          rowListTrans[i] = {
            ...rowListTrans[i],
            isExpand: true,
          };
          rowListTrans.splice(i + 1, 0, ...rowList[i].children);
          break;
        }
      }
      setRowList(rowListTrans);
    },
    [rowList],
  );

  // 收起
  const onClickFold = () => {};

  return (
    <div className="ant-tree ant-tree-icon-hide ant-tree-block-node draggable-tree">
      <div className="ant-tree-list" style={{ position: 'relative' }}>
        <div className="ant-tree-list-holder">
          <div>
            <div
              className="ant-tree-list-holder-inner"
              style={{ display: 'flex', flexDirection: 'column' }}
            >
              {rowList.map((i: any) => {
                return (
                  <TreeNode
                    key={i.key}
                    onClickFold={onClickFold}
                    onClickExpand={onClickExpand}
                    nodeData={i}
                    {...i}
                  />
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
export default tree;
